<template>
  <div>

    <div class="context-box">
      <!--状态条-->
      <el-steps :active="active" :simple="true">
        <el-step title="添加课程基础信息" @click="active = 1"></el-step>
        <el-step title="添加章节基础信息" @click="active = 2"></el-step>
        <el-step title="确认发布" @click="active = 3"></el-step>
      </el-steps>
      <!--添加课程基础信息-->
      <div v-if="active == 1" class="data">
        <div class="btn-box">
          <el-button type="primary" @click="saveCourse" size="small">保存信息</el-button>
        </div>
        <div class="data-box">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="课程名称">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="课程讲师">
              <el-select v-model="form.teacherId" placeholder="请选择课程讲师">
                <el-option v-for="t in teachers" :label="t.name" :value="t.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程分类">
              <el-cascader :options="options" :show-all-levels="true" v-model="form.subjectIds"></el-cascader>
            </el-form-item>
            <el-form-item label="收费课程" :disabled="true">
              <el-radio-group v-model="form.toll">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课程价格"
                          prop="price"
                          :rules="[
                                  { type: 'number', message: '课程价格必须为数字值'}
                                ]" >
              <el-input v-model.number="form.price" :disabled="!form.toll"></el-input>
            </el-form-item>
            <el-form-item label="课程封面">
              <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8002/eduoss/fileoss"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="conver" :src="conver" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="课程状态" :disabled="true">
              <el-radio-group v-model="form.status">
                <el-radio label="Draft" :disabled="true">未发布</el-radio>
                <el-radio label="Normal" :disabled="true">已发布</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课时"
                          prop="lessonNum"
                          :rules="[
                                  { type: 'number', message: '课时必须为数字值'}
                                ]" >
              <el-input type="input" v-model.number="form.lessonNum"></el-input>
            </el-form-item>
            <el-form-item label="课程简介">
              <tinymce :height="300" v-model="form.description"/>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!--添加章节基础信息-->
      <div v-if="active == 2" class="data">
        <div class="btn-box">
          <el-button type="primary" @click="showDialogChild" size="small">添加</el-button>
          <el-button type="primary" @click="importChapter" size="small">批量导入</el-button>
          <el-button type="danger" @click="deleteAll" size="small">删除全部</el-button>
          <el-button type="primary" @click="active = 1" size="small">上一步</el-button>
          <el-button type="primary" @click="nextStep" size="small">下一步</el-button>
        </div>
        <div>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column
              prop="sort"
              label="排序号"
              sortable
              width="120">
            </el-table-column>
            <el-table-column
              prop="title"
              label="章节名称"
              sortable
              width="180">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <div style="display: flex; justify-content: flex-end; width: 320px">
                  <el-button v-if="scope.row.pid == 0" type="success" size="mini" @click="saveChild(scope.row)">添加子级
                  </el-button>
                  <el-button v-if="!scope.row.videoId && scope.row.pid != 0" type="success" size="mini"
                             @click="uploadVideo(scope.row.id)">添加视频
                  </el-button>
                  <el-button v-if="scope.row.videoId" type="danger" size="mini" @click="deleteVideo(scope.row.id)">删除视频
                  </el-button>
                  <el-button v-if="scope.row.videoId" type="primary" size="mini">查看视频</el-button>
                  <el-button type="primary" size="mini" @click="updateOne(scope.row)">修改</el-button>
                  <el-button type="danger" size="mini" @click="deleteOne(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--确认发布-->
      <div v-if="active == 3" class="data">
        <div class="btn-box">
          <el-button type="primary" @click="active = 2" size="small">上一步</el-button>
          <el-button type="success" @click="confirmRelease" size="small">确认发布</el-button>
        </div>
        <div class="data-box-mini">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="课程名称">
              <el-input v-model="form.title" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="课程讲师">
              <el-select v-model="form.teacherId" placeholder="请选择课程讲师" :disabled="true">
                <el-option v-for="t in teachers" :label="t.name" :value="t.id" :disabled="true"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程分类">
              <el-cascader :options="options" :show-all-levels="true" v-model="form.subjectIds"
                           :disabled="true"></el-cascader>
            </el-form-item>
            <el-form-item label="收费课程" :disabled="true">
              <el-radio-group v-model="form.toll">
                <el-radio :label="true" :disabled="true">是</el-radio>
                <el-radio :label="false" :disabled="true">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课程价格"
                          prop="price"
                          :rules="[
                                  { type: 'number', message: '课程价格必须为数字值'}
                                ]" >
              <el-input v-model.number="form.price" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="课程封面">
              <img v-if="conver" :src="conver" class="avatar">
            </el-form-item>
            <el-form-item label="课程状态" :disabled="true">
              <el-radio-group v-model="form.status">
                <el-radio label="Draft" :disabled="true">未发布</el-radio>
                <el-radio label="Normal" :disabled="true">已发布</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="课时"
                          prop="lessonNum"
                          :rules="[
                                  { type: 'number', message: '课时必须为数字值'}
                                ]" >
              <el-input type="input" v-model.number="form.lessonNum" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="课程简介">
              <tinymce :height="300" v-model="form.description" :disabled="true"/>
            </el-form-item>
            <el-form-item label="课程章节">
              <el-table
                :data="tableData"
                :show-header="false"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                  prop="title">
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!--添加章节-->
      <el-dialog :title="title" :visible.sync="dialogChild">
        <el-form :model="chapter">
          <el-form-item v-if="showTitle" :label="belong" :label-width="formLabelWidth">
            <el-input v-model="pname" autocomplete="off" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="章节名称" :label-width="formLabelWidth">
            <el-input v-model="chapter.title" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="排序号" :label-width="formLabelWidth"
                        prop="sort"
                        :rules="[
                                  { required: true, message: '排序号不能为空'},
                                  { type: 'number', message: '排序号必须为数字值'}
                                ]"
          >
            <el-input v-model.number="chapter.sort" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialog">取 消</el-button>
          <el-button type="primary" @click="saveOne">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--批量导入-->
    <el-dialog title="批量导入课程章节" :visible.sync="dialogFormVisible">
      <span>文件名称后出现绿色勾即代表导入完毕</span>
      <span class="a-class">
        <a href="https://alan-guli.oss-cn-shenzhen.aliyuncs.com/excel/chapter-import.xlsx">点击下载导入模板</a>
      </span>
      <el-upload
        class="upload-demo"
        :on-success="uploadSuccess"
        :action="uploadUrl"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </el-dialog>
    <!--添加视频-->
    <el-dialog title="上传视频" :visible.sync="dialogVideo">
      <el-upload
        class="upload-demo"
        action="http://127.0.0.1:8003/vod/video/upload"
        :on-change="handleChangeVideo"
        :on-success="uploadVideoSuccess"
        :file-list="video.videos">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个视频文件</div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
  import teacher from "@/api/edu/teacher";
  import subject from "@/api/edu/subject";
  import chapter from "@/api/edu/chapter";
  import course from "@/api/edu/course";
  import Tinymce from '@/components/Tinymce';

  export default {
    components: {Tinymce},
    data() {
      return {
        // 控制状态栏
        active: 1,

        // 表单数据
        form: {
          status: 'Draft',
          toll: true,
          cover: '',
          teacherId: '',
          subjectIds: []
        },
        conver: '',

        // 下拉框的值
        teachers: [],
        options: [],

        // 添加章节
        courseId: '-1',
        dialogChild: false,
        chapter: {},
        title: "",
        belong: '所属课程',
        temp: '',
        pname: "Java从入门到入土",
        formLabelWidth: '100px',
        tableData: [],
        showTitle: true,

        loading: false,

        // 文件上传
        dialogFormVisible: false,
        fileList: [],
        uploadUrl: "http://127.0.0.1:8001/eduService/chapterImport/",

        // 视频上传
        dialogVideo: false,
        video: {videos: []}

      }
    },
    created() {
      this.getTeacherList();
      this.getSubjectList();
      this.getChapterList();
    },
    methods: {
      // 01 上传视频封面图片
      handleAvatarSuccess(res, file) {
        this.conver = res.data.url
        this.form.cover = this.conver
        console.log(this.form)
      },
      beforeAvatarUpload(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('上传封面图片大小不能超过 10MB!');
        }
        return isLt10M;
      },

      // 02 获取讲师列表
      getTeacherList() {
        teacher.getAll().then(response => {
          this.teachers = response.data.items;
        })
      },

      // 03 获取课程分类列表
      getSubjectList() {
        subject.getAll().then(response => {
          this.options = response.data.list;
        })
      },

      // 04 保存课程基础信息
      saveCourse() {
        var data = this.form;
        if (!(data.title) || !(data.teacherId) || !(data.subjectIds) || !(data.cover)) {
          this.$message({
            type: 'warning',
            message: '请填写数据后重试',
          });
          return;
        }
        if (this.courseId != -1) {
          data.subjectId = data.subjectIds[1];
          data.subjectParentId = data.subjectIds[0];
          course.updateOne(this.form).then(response => {
            this.courseId = response.data.courseId;
            this.pname = this.form.title;
            this.active = 2;
            this.loading = true;
            this.getChapterList();
            setInterval(() => {
              this.loading = false;
              clearInterval();
            }, 400)
          })
        } else {
          data.subjectId = data.subjectIds[1];
          data.subjectParentId = data.subjectIds[0];
          course.saveOne(this.form).then(response => {
            this.courseId = response.data.courseId;
            this.form.id = response.data.courseId;
            this.pname = this.form.title;
            this.active = 2;
            this.loading = true;
            setInterval(() => {
              this.loading = false;
              clearInterval();
            }, 400)
          })
        }

      },

      // 05 添加一个课程章节
      saveOne() {
        if (this.chapter.id) {
          this.chapter.courseId = this.courseId;
          chapter.updateOne(this.chapter).then(response => {
            this.dialogChild = false;
            this.chapter = {};
            this.getChapterList()
          })
        } else {
          this.chapter.courseId = this.courseId;
          chapter.saveOne(this.chapter).then(response => {
            this.dialogChild = false;
            this.chapter = {};
            this.getChapterList()
          })
        }
      },

      // 06 删除全部章节
      deleteAll() {
        this.$confirm('确定删除课程 - ' + this.pname + ' 全部章节 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          chapter.deleteAll(this.courseId).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
            this.getChapterList();
          })
        })
      },

      // 07 删除一个章节
      deleteOne(param) {
        this.$confirm('确定删除章节 - ' + param.title + ' ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            chapter.deleteOne(param.id).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getChapterList();
            })
          }
        )
      },

      // 08 修改
      updateOne(row) {
        this.showTitle = false;
        this.chapter = {...row};
        this.dialogChild = true;
      },

      // 09 添加子级
      saveChild(row) {
        this.chapter = {};
        this.showTitle = true;
        this.chapter.pid = row.id;
        this.belong = '所属章节';
        this.pname = row.title;
        this.chapter.id = '';
        this.dialogChild = true;
      },

      // 11 打开对话框
      showDialogChild() {
        this.pname = this.form.title;
        this.belong = '所属课程';
        this.chapter = {};
        this.showTitle = true;
        this.dialogChild = true;
        this.chapter.id = ''
      },

      // 12 关闭对话框
      cancelDialog() {
        this.dialogChild = false;
        this.chapter.id = ''
      },

      // 13 线程休眠
      sleep(n) {
        var start = new Date().getTime();
        while (true) {
          if (new Date().getTime() - start > n) {
            break;
          }
        }
      },

      // 14 确认发布
      confirmRelease() {
        course.confirmRelease(this.courseId).then(response => {
          this.$message({
            type: 'success',
            message: '发布成功!',
          });
          this.$router.push('/course')
        })
      },

      // 15 下一步
      nextStep() {
        if (this.tableData.length == 0) {
          this.$message({
            type: 'warning',
            message: '请填写数据后重试',
          });
          return;
        }
        this.active = 3
      },

      // 16 文件上传
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },

      // 18 批量导入
      importChapter() {
        this.dialogFormVisible = true
        this.uploadUrl = "http://127.0.0.1:8001/eduService/chapter/chapterImport/" + this.courseId;
      },

      // 19 课程章节批量导入成功提示
      uploadSuccess() {
        this.$message({
          type: 'success',
          message: '批量导入成功',
        });
      },

      // 19 视频上传
      uploadVideo(chapterId) {
        this.dialogVideo = true;
        this.chapter = {id: chapterId};
        this.video.videos = [];
      },
      handleChangeVideo(file, fileList) {
        this.video.videos = fileList.slice(-3);
      },
      uploadVideoSuccess(response, file, fileList) {
        this.chapter.videoId = response.data.id;
        chapter.updateOne(this.chapter).then(
          this.uploadSuccessAfter()
        );
      },
      uploadSuccessAfter() {
        this.getChapterList();
        this.$message({
          type: 'success',
          message: '视频上传成功!',
        })
      },


      // 20 删除视频
      deleteVideo(id) {
        this.$confirm('确定删除视频 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            chapter.deleteVideo(id).then(response => {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getChapterList();
            })
          }
        )
      },

      // 获取所有的章节信息
      getChapterList() {
        if (this.courseId != -1) {
          chapter.getAll(this.courseId).then(response => {
            this.tableData = response.data.list;
          })
        }
      },
    },
    mounted() {
    }, watch: {
      courseId(newVal, oldVal) {
        this.uploadUrl = "http://127.0.0.1:8001/eduService/chapter/chapterImport/" + newVal;
      },
      dialogFormVisible(newVal, oldVal) {
        if (oldVal) {
          this.getChapterList()
        }
      },
      dialogVideo(newVal, oldVal) {
        if (oldVal) {
          this.getChapterList()
        }
      },
    }
  };
</script>

<style>

  .data {
    margin-top: 20px;
  }

  .btn-box {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .context-box {
    margin: 60px auto;
    width: 90%;
    border: #f4f4f5 solid 1px;
    padding: 20px;
    background: #fefefe;
  }

  .context-box .data-box {
    width: 80%;
    margin: 40px auto;
    border: 0;
  }

  .data-box-mini {
    width: 60%;
    margin: 40px auto;
    border: 1px solid #d3dce6;
    padding: 40px 20px;
    border-radius: 3px;
  }


  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 260px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 260px;
    height: 160px;
    display: block;
  }

  .a-class {
    display: block;
    margin: 20px 0;
    color: #409EFF;
  }

  .tinymce-container {
    line-height: 29px;
  }

</style>
